from http.client import HTTPException
from typing import List, Tuple

from fastapi import APIRouter, Request
from fastapi import Depends
from requests import Session

from config.get_db import get_db
from core.dao.cms_gaode_fence_dao import CmsGaodeFenceDao
from core.entity.do.models import CmsGaodeFence
from core.entity.vo.common import CrudResponse
from core.entity.vo.view_models import CmsGaodeFenceVO, PaginationQuery, CmsGaodeFenceTerminalVO, CmsGaodeFenceResponse, \
    PageObjectResponse, PaginationQueryForPage
from core.service.cms_gaode_fence_service import CmsGaodeFenceService
from core.service.cms_gaode_fence_terminal_service import CmsGaodeFenceTerminalService
from utils.log_util import *
from utils.response_util import *
from utils.time_format_util import list_format_datetime
from utils.page_util import get_page_obj, get_new_page_obj
from utils.uuid import UUID

gaodeFenceController = APIRouter()


@gaodeFenceController.get("/gaode_fence/list", response_model=PageObjectResponse)
async def list_gaode_fences(query: PaginationQuery = Depends(),
                            query_db: Session = Depends(get_db)):
    try:
        response = CmsGaodeFenceService.list_cms_gaode_fences(query_db, query)
        total = response.total
        # list_format_datetime(response.data)
        # 分页操作
        page_result_after = get_new_page_obj(response.data, query.page_num, query.page_size, total)
        return response_200(data=page_result_after, message="获取成功")

    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@gaodeFenceController.post("/gaode_fence/query_by_id", response_model=CmsGaodeFenceVO)
async def get_gaode_fence_by_id(request: Request, id: int, query_db: Session = Depends(get_db)):
    try:
        # 获取全量数据
        cms_gaode_fence = CmsGaodeFenceService.get_cms_gaode_fence_by_id(query_db, id)
        logger.info('获取成功')
        return response_200(data=cms_gaode_fence, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@gaodeFenceController.post("/gaode_fence/query_by_fence_id", response_model=CmsGaodeFenceVO)
async def get_gaode_fence_by_fence_id(request: Request, fence_id: str, query_db: Session = Depends(get_db)):
    try:
        # 获取全量数据
        cms_gaode_fence = CmsGaodeFenceService.get_cms_gaode_fence_by_fence_id(query_db, fence_id)
        logger.info('获取成功')
        return response_200(data=cms_gaode_fence, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@gaodeFenceController.post("/gaode_fence/query_like_fence_name", response_model=CmsGaodeFenceVO)
async def get_gaode_fence_like_fence_name(request: Request, fence_name: str, query_db: Session = Depends(get_db)):
    try:
        # 获取全量数据
        cms_gaode_fence_list = CmsGaodeFenceService.get_cms_gaode_fence_like_name(query_db, fence_name)
        logger.info('获取成功')
        return response_200(data=cms_gaode_fence_list, message="获取成功")
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@gaodeFenceController.post("/gaode_fence/add", response_model=CrudResponse)
async def add_gaode_fence(request: Request, cms_gaode_fence: CmsGaodeFenceVO, query_db: Session = Depends(get_db)):
    try:
        # Loop through each car in the cars array
        cms_gaode_fence_result = await CmsGaodeFenceService.add_cms_gaode_fence(request, query_db, cms_gaode_fence)
        if not cms_gaode_fence_result.is_success:
            logger.warning(cms_gaode_fence_result.message)
            return response_400(data="", message=cms_gaode_fence_result.message)
        terminal_fence_list = []
        for car in cms_gaode_fence.cars:
            # Create and save CmsGaodeFenceTerminalVO for each car
            terminal_fence = CmsGaodeFenceTerminalVO(
                id=UUID().uuid(),
                service_id=cms_gaode_fence.service_id,
                fence_id=cms_gaode_fence.fence_id,
                terminal_id=car,
                state=cms_gaode_fence.state,
                create_time=cms_gaode_fence.create_time,
                create_by=cms_gaode_fence.create_by,
                update_time=cms_gaode_fence.update_time,
                update_by=cms_gaode_fence.update_by
            )
            terminal_fence_list.append(terminal_fence)

        try:
            cms_gaode_fence_terminal_result = CmsGaodeFenceTerminalService.bind_cms_gaode_fence_terminal_batch(
                request, query_db, terminal_fence_list)

            if not cms_gaode_fence_terminal_result.is_success:
                logger.warning(cms_gaode_fence_terminal_result.message)
                return response_400(data="", message=cms_gaode_fence_terminal_result.message)
        except Exception as e:
            logger.exception(e)
            return response_500(data="", message=str(e))

        return response_200(data="All fences added successfully", message="Success")

    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@gaodeFenceController.post("/gaode_fence/edit", response_model=CrudResponse)
def edit_gaode_fence(request: Request, cms_gaode_fence: CmsGaodeFenceVO, query_db: Session = Depends(get_db)):
    try:
        # fence: CmsGaodeFence = CmsGaodeFenceService.get_cms_gaode_fence_by_id(query_db, int(cms_gaode_fence.id))
        fence: CmsGaodeFence = CmsGaodeFenceDao.get_cms_gaode_fence_by_id(query_db, cms_gaode_fence.id)
        if fence is None:
            raise ValueError("该电子围栏不存在")
        if cms_gaode_fence.polygon_points is None:
            cms_gaode_fence.polygon_points = fence.polygon_points
        if cms_gaode_fence.fence_name is None:
            cms_gaode_fence.fence_name = fence.fence_name
        cms_gaode_fence_result = CmsGaodeFenceService.edit_cms_gaode_fence(request, query_db, cms_gaode_fence)
        if not cms_gaode_fence_result.is_success:
            logger.info(cms_gaode_fence_result.message)
            return response_200(data=cms_gaode_fence_result, message=cms_gaode_fence_result.message)
        terminal_fence_list = []
        for car in cms_gaode_fence.cars:
            # Create and save CmsGaodeFenceTerminalVO for each car
            terminal_fence = CmsGaodeFenceTerminalVO(
                id=UUID().uuid(),
                service_id=cms_gaode_fence.service_id,
                fence_id=cms_gaode_fence.fence_id,
                terminal_id=car,
                state=cms_gaode_fence.state,
                create_time=cms_gaode_fence.create_time,
                create_by=cms_gaode_fence.create_by,
                update_time=cms_gaode_fence.update_time,
                update_by=cms_gaode_fence.update_by
            )
            terminal_fence_list.append(terminal_fence)

        try:
            # 解绑之前的
            CmsGaodeFenceTerminalService.unbind_cms_gaode_fence_terminal_batch(query_db, cms_gaode_fence.fence_id)

            cms_gaode_fence_terminal_result = CmsGaodeFenceTerminalService.bind_cms_gaode_fence_terminal_batch(
                request, query_db, terminal_fence_list)

            if not cms_gaode_fence_terminal_result.is_success:
                logger.warning(cms_gaode_fence_terminal_result.message)
                return response_400(data="", message=cms_gaode_fence_terminal_result.message)
        except Exception as e:
            logger.exception(e)
            return response_500(data="", message=str(e))

        return response_200(data="All fences added successfully", message="Success")

    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))


@gaodeFenceController.post("/gaode_fence/delete", response_model=CrudResponse)
async def delete_gaode_fence(request: Request, cms_gaode_fence: CmsGaodeFenceVO, query_db: Session = Depends(get_db)):
    try:
        delete_gaode_fence_result = CmsGaodeFenceService.delete_cms_gaode_fence(query_db, cms_gaode_fence.id,
                                                                                cms_gaode_fence.service_id,
                                                                                cms_gaode_fence.fence_id)
        if delete_gaode_fence_result.is_success:
            logger.info(delete_gaode_fence_result.message)
            return response_200(data=delete_gaode_fence_result, message=delete_gaode_fence_result.message)
        else:
            logger.warning(delete_gaode_fence_result.message)
            return response_400(data="", message=delete_gaode_fence_result.message)
    except Exception as e:
        logger.exception(e)
        return response_500(data="", message=str(e))
